async function fetchFbaShipments() {
  const endpoint = await getEndpoint()
  let link = `${await getOrigin()}/gp/ssof/shipping-queue.html/ref=xx_fbashipq_favb_xx#`

  let listData = await new Promise((resolve, reject) => {
    openUrlAndExecScript(link, 'apps/fba_shipments/list_content.js', resolve);
  });

  let shipments = listData.shipments
  let delShipmentIds = listData.delShipmentIds

  const present_shipments_link = `https://api.miraazzurra.com/amazon/shipment/existed?endpoint=${endpoint}`
  let existed_shipment_ids = await fetch(present_shipments_link).then(response => response.json());
  shipments = shipments.filter(r => !existed_shipment_ids.includes(r.shipmentId))
  
  let results = []
  for (var i = 0; i < shipments.length; i++) {
    console.log(`fetchFbaShipments progress: ${i+1}/${shipments.length}`)
    let shipment = shipments[i]
    let details = await getShipmentDetails(shipment);
    results.push(details)
  }
  console.log(results.flat())

  const uploadUrl = 'https://api.miraazzurra.com/amazon/shipment/import';
  let retryTime = 0;
  while (retryTime < 3) {
    try {
      await post(uploadUrl, { shipments: results.flat() });
      retryTime = 4; // 成功后退出循环
    } catch (error) {
      retryTime++;
      if (retryTime >= 3) {
        console.log('上传失败')
      }
    }
  }

  const deleteUrl = 'https://api.miraazzurra.com/amazon/shipment/discard';
  let ids = delShipmentIds.filter(id => existed_shipment_ids.includes(id))
  await post(deleteUrl, { endpoint: endpoint, shipmentIds: ids });

  return results;
}

async function getShipmentDetails(shipment) {
  const endpoint = await getEndpoint()
  let link = `${await getOrigin()}/fba/inbound-shipment/summary/${shipment.shipmentId}/contents`
  let details = await new Promise((resolve, reject) => {
    openUrlAndExecScript(link, 'apps/fba_shipments/detail_content.js', resolve);
  });

  return details.map(detail => {
    return {
      endpoint: endpoint,
      created_date: shipment.createdDate,
      fba_id: shipment.shipmentId,
      sku_count: shipment.mskus,
      total_quantity: shipment.expectedQuantity,
      sku: detail.merchantSKU,
      sku_quantity: detail.expectedQuantity
    };
  })
}
